/**
 * 
 */
package com.puccampinas.finalproject.core.initiate;

import java.io.FileInputStream;
import java.util.Properties;

import com.puccampinas.finalproject.core.logs.LogUtils;
import com.puccampinas.finalproject.core.logs.LoggerType;
import com.puccampinas.finalproject.core.persistence.jdbc.DataSourceProvider;
import com.puccampinas.finalproject.core.util.ConfigurationProvider;
import com.puccampinas.finalproject.rest.WebServerManager;

public class Startup {

	private static String PATH;
    private static final String APPLICATION_PROPERTIES = "properties/application.properties";
    private static final String ATTACK_GAME_DATABASE_PROPERTIES = "properties/database.properties";
    private static final String JETTY_PROPERTIES = "properties/jetty.properties";
    private static final String LOG4J_XML = "xml/log4j.xml";
    
    public Startup() {
        this("conf/" + Main.DEFAULT_ENVIRONMENT + "/");
    }

    public Startup(String baseConfigurationFolder) {
        PATH = baseConfigurationFolder;
    }

    public void startAll() throws Exception {

        initConfiguration();
        initLogUtils();
        initWebserver();
        initializeDatabaseConf();
        
    }

   

    private static void initWebserver() {

        System.out.print("Initializing Jetty...");
        Thread thread = new Thread(new WebServerManager(ConfigurationProvider.getInstance().getSmartProperty(PATH + JETTY_PROPERTIES)), "WebServerManager");
        thread.start();

        System.out.println("[OK]");
    }

    private static void initConfiguration() {

        ConfigurationProvider.init("./");

        System.out.print("Loading Application Properties...");

        try {

            Properties properties = new Properties();
            properties.load(new FileInputStream(ConfigurationProvider.getInstance().getDirectory() + PATH + APPLICATION_PROPERTIES));  
            
            System.out.println("[OK]");

        } catch (Exception e) {
            LogUtils.error(LoggerType.EXCEPTIONS, "Error initializing Application Configuration. SYSTEM WILL NOT START!", e);
            System.out.println("[FAIL]");
        }
    }

    private static void initLogUtils() throws Exception {

        System.out.print("Initializing LogUtils database configuration...");
        LogUtils.init(ConfigurationProvider.getInstance().getDirectory() + PATH + LOG4J_XML, Boolean.TRUE);
        System.out.println("[OK]");

    }

    private void initializeDatabaseConf() throws Exception {
        Properties databasePropertiesFile = new Properties();

        System.out.print("Initializing Attack Game database configuration...");
        databasePropertiesFile.load(new FileInputStream(ConfigurationProvider.getInstance().getDirectory() + PATH + ATTACK_GAME_DATABASE_PROPERTIES));
        DataSourceProvider.init(databasePropertiesFile);

        System.out.println("[OK]");

    }
}